<template>
    <div class="hotspot-icon h-full">
        <el-form :inline="true" :model="searchform">
            <div class="flex justify-between mb-3">
                <el-space>
                    <el-button type="success" size="default" @click="toggleExpand">
                        <i class="iconfont icon-jiantou_shangxiaqiehuan"></i>{{ isExpandAll ? '收起' : '展开' }}
                    </el-button>
                    <el-button size="default" type="primary" :icon="Plus" @click="openEdit('add')">新增</el-button>
                    <el-button type="danger" :icon="Delete" @click="openEdit('add')">删除</el-button>
                </el-space>
                <el-space>
                    <el-input v-model="searchform.name" placeholder="请输入菜单名称" clearable style="width:200px;"/>
                    <el-button type="primary" @click="getList" :icon="Search">查询</el-button>
                </el-space>
            </div>
        </el-form>
        <div class="table-section grid" style="height:calc(100% - 32px - 0.75rem)">
            <el-table ref="tableRef" :data="tableData" border row-key="id" :default-expand-all="isExpandAll" max-height="795">
                <el-table-column prop="name" label="菜单名"/>
                <el-table-column prop="status" label="状态" width="80">
                    <template #default="scope">
                        <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="图标" header-align="center" align="center" width="80">
                    <template #default="scope">
                        <component v-if="scope.row.icon" class="w-[20px] mr-2 ml-1" :is="scope.row.icon"/>
                    </template>
                </el-table-column>

                <el-table-column label="类型" header-align="center" align="center" width="100">
                    <template #default="scope">
                        <el-tag type="warning" effect="light" v-if="scope.row.node_type=='1'">目录</el-tag>
                        <el-tag type="primary" effect="light" v-else-if="scope.row.node_type=='2'">菜单</el-tag>
                        <el-tag type="danger" effect="light" v-else-if="scope.row.node_type=='3'">权限</el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="order_num" label="排序" width="80"/>
                <el-table-column prop="path" label="路由"/>
                <el-table-column prop="component" label="组件路径"/>
                <el-table-column prop="perms" label="权限字段">
                    <template #default="scope">
                        <template v-if="scope.row.node_type=='3'">
                            <el-tag type="success" effect="light" v-for="item of scope.row.perms.split(',')">{{ item }}</el-tag>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" align="center" width="280">
                    <template #default="scope">
                        <div class="flex" style="justify-content: flex-end">
                            <el-button type="primary" plain @click="openEdit('add',scope.row)" v-if="scope.row.node_type!=='3'">新增</el-button>
                            <el-button type="success" plain @click="openEdit('update',scope.row)">编辑</el-button>
                            <el-button type="danger" plain @click="deleteItem(scope.row.id)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>

    <!--  添加项目弹框  -->
    <el-dialog v-model="editData.visible" :title="editData.title" center :show-close="false" width="50%" top="10vh" :close-on-click-modal="false">
        <div class="edit-form">
            <el-form :model="editData.form" label-width="auto" style="width:100%" ref="formRef">
                <el-row :gutter="50">
                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="节点类型" prop="node_type">
                            <el-radio-group v-model="editData.form.node_type">
                                <el-radio value="1">目录</el-radio>
                                <el-radio value="2">菜单</el-radio>
                                <el-radio value="3">权限</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="editData.form.node_type==2">
                        <el-form-item label="菜单类型" prop="menu_type">
                            <el-radio-group v-model="editData.form.menu_type">
                                <el-radio value="1">路由</el-radio>
                                <el-radio value="2">iframe</el-radio>
                                <el-radio value="3">外链</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="上级菜单">
                            <el-cascader
                                style="width:100%"
                                node-key="id"
                                v-model="editData.form.parent_id"
                                :show-all-levels="false"
                                :options="upLevelMenus"
                                placeholder="请选择上级菜单"
                                :props="{label:'name',value:'id',checkStrictly:false}"
                                clearable
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="节点名称" prop="name">
                            <el-input v-model="editData.form.name" placeholder="请输入节点名称"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item class="relative" label="图标" prop="icon">
                            <el-input v-model="editData.form.icon" placeholder="请选择图标"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="editData.form.node_type==2 && editData.form.menu_type!=3">
                        <el-form-item label="组件路径">
                            <el-input v-model="editData.form.component" placeholder="请输入组件路径"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="editData.form.node_type==2 && editData.form.menu_type!=3">
                        <el-form-item label="路由地址" prop="path">
                            <el-input v-model="editData.form.path" placeholder="请输入路由地址"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="editData.form.node_type==2 && editData.form.menu_type!=1 ">
                        <el-form-item label="url地址" prop="url">
                            <el-input v-model="editData.form.url" placeholder="请输入url地址"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-show="editData.form.node_type==3">
                        <el-form-item>
                            <el-input v-model="editData.form.perms" placeholder="请输入权限标识" maxlength="100"/>
                            <template #label>
                                <span>
                                  权限字符
                                  <el-tooltip content="控制器中定义的权限字符，如： @Permissions('system:menu:list')">
                                    <component class="w-[18px] inline" is="Warning"/>
                                  </el-tooltip>
                                </span>
                            </template>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="排序" prop="order_num">
                            <el-input v-model="editData.form.order_num" type="number" placeholder="请输入排序"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="显示状态" prop="status">
                            <el-switch v-model="editData.form.status" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editData.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </div>
        </template>
    </el-dialog>

</template>
<script setup>
import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { Delete, Edit, Search, Plus } from '@element-plus/icons-vue'
import menuApi from 'api/model/menu.js'
import { convertToTree, filterTreeByKeyValue } from '@/utils/util.js'

/******************************* 菜单的增删改查 *******************************/

const searchform = reactive({
    name: '',
})

// 表格数据（树结构）
const tableData = ref([])

// 表格ref 对象
const tableRef = ref()

// 是否展开所有
const isExpandAll = ref(true)

// 展开和折叠切换
const toggleExpand = () => {
    isExpandAll.value = !isExpandAll.value
    nextTick(() => {
        tableData.value.forEach(item => {
            tableRef.value.toggleRowExpansion(item, isExpandAll.value)
        })
    })
}

// 编辑相关数据
const editData = reactive({
    type: 'add',
    visible: false,
    form: {
        id: '',
        parent_id: '',
        node_type: '1',
        menu_type: '1',
        name: '',
        icon: '',
        path: '',
        url: '',
        component: '',
        order_num: '',
        perms: '',
        desc: '',
        status: true,
    }
})

// 项目表单ref 对象
const formRef = ref()

// 打开编辑或新增
const openEdit = (type, item) => {
    editData.title = type === 'add' ? '新增类型' : '编辑类型'
    editData.visible = true
    editData.type = type
    nextTick(() => {
        formRef.value.resetFields()
        if (type === 'update') {
            const {
                id,
                parent_id,
                node_type,
                menu_type,
                name,
                icon,
                path,
                url,
                component,
                order_num,
                perms,
                desc,
                status
            } = item || {}

            editData.form.id = id
            editData.form.parent_id = parent_id
            editData.form.node_type = node_type
            editData.form.menu_type = menu_type
            editData.form.name = name
            editData.form.icon = icon
            editData.form.path = path
            editData.form.url = url
            editData.form.component = component
            editData.form.order_num = order_num
            editData.form.perms = perms
            editData.form.desc = desc
            editData.form.status = status
        }

        // 新增子级菜单时，默认选中父级菜单
        if (type === 'add' && item) {
            editData.form.id = ''
            editData.form.node_type = item.node_type == 1 ? '2' : '3'
            editData.form.parent_id = item.id
        }
    })
}

// 更具选择的菜单类型获取上级菜单
const upLevelMenus = computed(() => {
    const value = editData.form.node_type == 3 ? 2 : 1
    const treeList = filterTreeByKeyValue(tableData.value, 'node_type', value, editData.form.id)
    console.log(treeList, '=================')
    return treeList
})

/**
 * 提交表单
 */
function submitForm () {
    editData.type === 'add' ? addItem() : updateItem()
}

/**
 *  获取列表
 */
async function getList () {
    const { code, data = [] } = await menuApi.list.get()
    // 将扁平化数组转换为嵌套结构
    tableData.value = convertToTree(data)
}

/**
 *  新增操作
 */
async function addItem () {
    const parent_id = Array.isArray(editData.form.parent_id) ? editData.form.parent_id[0] : editData.form.parent_id
    const { code, data = [] } = await menuApi.add.post({ ...editData.form, parent_id })
    if (code === 0) {
        ElMessage.success('新增成功')
        editData.visible = false
        getList()
    }
}

/**
 *  更新操作
 */
async function updateItem () {
    const { code, data = [] } = await menuApi.update.post(editData.form)
    if (code === 0) {
        editData.visible = false
        getList()
        ElMessage.success('编辑成功')
    }
}

/**
 * 删除操作
 * @param id
 */
function deleteItem (id) {
    /*删除二次确认*/
    ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const { code, data = [] } = await menuApi.delete.post({ id })
        if (code === 0) {
            getList()
            ElMessage.success('删除成功')
        }
    }).catch(() => {
        ElMessage.info('取消删除')
    })
}

onMounted(() => {
    getList()
})

</script>


<style lang="less">


</style>